//
//  SelectAddressVC.swift
//  ShareUmbrella
//
//  Created by keng fu on 2017/9/8.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import YSKit
import RxSwift

class SelectAddressVC: YSBaseViewController {
    let searchView = UISearchBar()
    let resultTableView = UITableView()
    var dataArray = Array<Any>()
    var histroyDataArray = Array<String>()
    let histroyTableView = UITableView()

    let search = AMapSearchAPI()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.title = "选择位置"
        
        search?.delegate = self
        
        searchView.ys.customize { (view) in
            self.view.addSubview(view)
            view.snp.makeConstraints({ (make) in
                make.leading.trailing.top.equalTo(self.view)
                make.height.equalTo(50)
            })
            searchView.becomeFirstResponder()
        }
        
        resultTableView.ys.customize { (tableView) in
            tableView.delegate = self
            tableView.dataSource = self
            tableView.separatorStyle = .none
            self.view.addSubview(tableView)
            tableView.snp.makeConstraints({ (make) in
                make.leading.trailing.equalTo(self.view)
                make.top.equalTo(searchView.snp.bottom)
                make.bottom.equalTo(self.view.snp.bottom)
            })
        }
        
        searchView
            .rx.text
            .takeUntil(self.rx.deallocated)
            .throttle(0.3, scheduler: MainScheduler.instance)
            .filter({ [weak self](text) -> Bool in
                guard let  `self` = self else {
                    return true
                }
                let trimText = (text ?? "").trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
                if trimText.lengthOfBytes(using: String.Encoding.utf8) > 0 {
                    return true
                }
                return false
            })
            .subscribe(onNext: { [weak self](text) in
                guard let  `self` = self else {
                    return
                }
                let trimText = (text ?? "").trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
                //处理搜索请求
                
                let request = AMapPOIKeywordsSearchRequest()
                request.keywords = trimText
                request.requireExtension = true
                if let g = Location.locationReGeocode.value {
                    request.city = g.city
                }
                
                request.cityLimit = true
                request.requireSubPOIs = true
                self.search?.aMapPOIKeywordsSearch(request)
                
                self.histroyTableView.isHidden = true
            })
        
        guard Defaults[DefaultsKey<Array<String>?>("histroy_address")] != nil else {
            return;
        }
        
        
        histroyTableView.ys.customize { (tableView) in
            tableView.delegate = self
            tableView.dataSource = self
            tableView.separatorStyle = .none
            self.view.addSubview(tableView)
            tableView.snp.makeConstraints({ (make) in
                make.leading.trailing.equalTo(self.view)
                make.top.equalTo(searchView.snp.bottom)
                make.bottom.equalTo(self.view.snp.bottom)
            })
        }
        
        self.histroyDataArray = Defaults[DefaultsKey<Array<String>?>("histroy_address")]!
        self.resultTableView.reloadData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override open func beforePopNext(_ withdata:Any?){
        
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension SelectAddressVC : AMapSearchDelegate{
    
    func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
        
        if response.count == 0 {
            return;
        }
        
        let tempArray = NSMutableArray()
        for tip in response.pois {
            let ads = AddressModel()
            ads.uid = tip.uid;
            ads.name = tip.name;
            ads.district = tip.district;
            ads.address = tip.address;
            ads.adcode = tip.adcode;
            ads.latitude = Double(tip.location.latitude);
            ads.longitude = Double(tip.location.longitude);
            
            tempArray.add(ads)
            
        }
        
        self.dataArray = tempArray as! Array<Any>
        resultTableView.reloadData()
    }
    
    func aMapSearchRequest(_ request: Any!, didFailWithError error: Error!) {
        print(error.localizedDescription);
    }
    
    
}

extension SelectAddressVC : UITableViewDelegate, UITableViewDataSource{
    //分组个数
    func numberOfRowsInSection(section: Int) -> Int{
        return 1
    }
    
    //cell 个数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == self.histroyTableView {
            return histroyDataArray.count
        }
        return dataArray.count
    }
    
    //创建tableViewCell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        
        let cellIndenttifier:String = "CellIndenttifier";
        
        let cell:UITableViewCell  =  UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: cellIndenttifier);
        
        if histroyTableView == tableView {
            cell.textLabel?.text = histroyDataArray[indexPath.row] 
        }else{
            let addressModel = self.dataArray[indexPath.row] as! AddressModel
            cell.textLabel?.text = addressModel.address
            cell.detailTextLabel?.text = addressModel.name
        }
        
        return cell
    }
    
    //tablViewCell 高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 50.0
    }
    
    
    //tableView 点击事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        tableView.deselectRow(at: indexPath as IndexPath, animated: true)
        if tableView == self.histroyTableView {
            let request = AMapPOIKeywordsSearchRequest()
            request.keywords = histroyDataArray[indexPath.row]
            request.requireExtension = true
            if let g = Location.locationReGeocode.value {
                request.city = g.city
            }
            
            request.cityLimit = true
            request.requireSubPOIs = true
            self.search?.aMapPOIKeywordsSearch(request)
            self.histroyTableView.isHidden = true
            self.searchView.text = histroyDataArray[indexPath.row]
        }else{
            var historyArray = Defaults[DefaultsKey<Array<String>?>("histroy_address")]
            if historyArray == nil {
                historyArray = []
            }
            let lastModel = self.dataArray[indexPath.row] as! AddressModel;
            historyArray?.insert(lastModel.address, at: 0)
            if (historyArray?.count)! > 10 {
                historyArray?.remove(at: 10)
            }
            Defaults[DefaultsKey<Array<String>?>("histroy_address")] = historyArray
            
            self.ys.pop(nil , animated: true, withdata: self.dataArray[indexPath.row])
        }
    }
}
